package fel.via.cz.thewolfofwallstreet;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import fel.via.cz.thewolfofwallstreet.cache.UserCompaniesSQLiteCache;
import fel.via.cz.thewolfofwallstreet.components.ShareInfoTabHost;
import fel.via.cz.thewolfofwallstreet.components.SharesListView;
import fel.via.cz.thewolfofwallstreet.enums.AppViewState;

public class MainActivity extends Activity {


    //static public final String serverAddress = "http://8.21.28.81:8085/";
    static public final String serverAddress = "http://10.0.2.2:8080/";

    private AppViewState appViewState;
    private SharesListView sharesListView;
    private ShareInfoTabHost shareInfoTabHost;
    private JSONArray companies;
    private Map<String, Integer> myCompanies;
    private String userName;
    private double userMoney;
    private UserCompaniesSQLiteCache cache;
    private int selectedIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        this.initialize();
    }

    private void initialize() {
        Bundle extras = this.getIntent().getExtras();
        if (extras != null)
            this.userName = extras.getString("USER_NAME");

        this.cache = new UserCompaniesSQLiteCache(this);
        this.companies = new JSONArray();
        this.appViewState = AppViewState.Sale;
        this.sharesListView = new SharesListView(this);
        this.shareInfoTabHost = new ShareInfoTabHost(this);
        this.setSharesListViewItemOnClick();
        this.setSharesJsonDataFromServer();
    }

    private void setSharesListViewItemOnClick() {
        this.sharesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    selectedIndex = i;
                    shareInfoTabHost.setTabsContent(companies.getJSONObject(i), appViewState, userMoney);
                } catch (JSONException e) {
                    Log.e("JSONObject error: ", e.toString());
                }
            }
        });
    }

    private void setupSharesListView(JSONArray companies) {
        this.companies = companies;
        this.sharesListView.setup(companies);
        if (companies.length() > 0 || appViewState == AppViewState.Purchase) {
            this.sharesListView.selectSpecificItem(selectedIndex);
            try {
                shareInfoTabHost.setTabsContent(companies.getJSONObject(selectedIndex), appViewState, userMoney);
            } catch (JSONException e) {
                Log.e("JSONObject set tab content error: ", e.toString());
            }
        } else {
            shareInfoTabHost.disabledControls();
        }
    }

    public void setSharesJsonDataFromServer() {
        setUserMoney();
    }

    private void setUserMoney() {
        final String url = serverAddress + "wolfofwallstreet/money/" + userName;

        // prepare the Request
        JsonArrayRequest getRequest = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        // display response
                        Log.d("Response", response.toString());
                        if(response.length() > 0)
                            try {
                                userMoney = response.getDouble(0);
                                switch (appViewState) {
                                    case Sale:
                                        setSaleSharesJsonData();
                                        break;
                                    case Purchase:
                                        setPurchaseSharesJsonData();
                                        break;
                                }
                            } catch (JSONException e) {
                                Log.e("Error.USER MONEY", e.toString());
                            }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error.Response", error.toString());
                    }
                }
        ) {
            @Override
            public HashMap<String, String> getParams() {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("Accept", "application/json");
                return params;
            }
        };
        // add it to the RequestQueue
        LoginActivity.requestQueue.add(getRequest);
    }

    public void BuyOrSellEvent() {
        cache.clearCacheTable();
        setSharesJsonDataFromServer();
    }

    private void setSaleSharesJsonData() {
        String url_user_companies = serverAddress + "wolfofwallstreet/shares/" + userName;

        JSONArray ja = cache.getUserCompanies();
        if (ja.length() > 0) {
            setupSharesListView(ja);
            return;
        }

        // prepare the Request
        JsonArrayRequest getRequest = new JsonArrayRequest(url_user_companies,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        // display response
                        Log.d("Response", response.toString());
                        setMyCompaniesJsonArray(response);
                        setMyCompaniesFromAllCompanies();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error.Response", error.toString());
                    }
                }
        ) {
            @Override
            public HashMap<String, String> getParams() {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("Accept", "application/json");
                return params;
            }
        };
        // add it to the RequestQueue
        LoginActivity.requestQueue.add(getRequest);
    }

    private void setMyCompaniesFromAllCompanies() {
        final String url_all_companies = serverAddress + "wolfofwallstreet/companies";
        // prepare the Request
        JsonArrayRequest getRequestAll = new JsonArrayRequest(url_all_companies,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        // display response
                        Log.d("Response", response.toString());
                        setupSharesListView(getMyCompaniesListInfo(response));
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error.Response", error.toString());
                    }
                }
        ) {
            @Override
            public HashMap<String, String> getParams() {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("Accept", "application/json");
                return params;
            }
        };
        getRequestAll.setRetryPolicy(new DefaultRetryPolicy(
                60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        // add it to the RequestQueue
        LoginActivity.requestQueue.add(getRequestAll);
    }

    private void setMyCompaniesJsonArray(JSONArray companies) {
        myCompanies = new HashMap<String, Integer>();
        for (int i = 0; i < companies.length(); i++) {
            try {
                JSONObject company = companies.getJSONObject(i);
                myCompanies.put(company.getString("company"), company.getInt("stockCount"));
            } catch (JSONException e) {
                Log.e("JSONObject set my companies error: ", e.toString());
            }
        }
    }

    private JSONArray getMyCompaniesListInfo(JSONArray allCompanies) {
        JSONArray result = new JSONArray();
        for (int i = 0; i < allCompanies.length(); i++) {
            try {
                JSONObject company = allCompanies.getJSONObject(i);
                if (myCompanies.containsKey(company.getString("name"))) {
                    company.put("stockCount", myCompanies.get(company.getString("name")));
                    result.put(company);
                }
            } catch (JSONException e) {
                Log.e("JSONObject get my companies error: ", e.toString());
            }
        }

        if (result.length() > 0)
            cache.saveUserCompanies(result);
        return result;
    }

    private void setPurchaseSharesJsonData() {
        final String url = serverAddress + "wolfofwallstreet/companies";          //10.0.2.2 --- 127.0.0.1

        // prepare the Request
        JsonArrayRequest getRequest = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        // display response
                        Log.d("Response", response.toString());
                        setupSharesListView(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error.Response", error.toString());
                    }
                }
        ) {
            @Override
            public HashMap<String, String> getParams() {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("Accept", "application/json");
                return params;
            }
        };

        getRequest.setRetryPolicy(new DefaultRetryPolicy(
                60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        // add it to the RequestQueue
        LoginActivity.requestQueue.add(getRequest);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        selectedIndex = 0;

        if (id == R.id.action_sale) {
            this.appViewState = AppViewState.Sale;
        }

        if (id == R.id.action_purchase) {
            this.appViewState = AppViewState.Purchase;
        }

        setSharesJsonDataFromServer();
        return super.onOptionsItemSelected(item);
    }
}
